/**
 *****************************************************************************
 * DESC ：. 
 * Author : Junwei Zhang 
 * CREATEDATE ：2012-7-3 
 * MODIFYLIST ：       	Name 			 Date 			Reason/Contents
 * 				------------------------------------------------------ 
 * 				 	Junwei Zhang     2012-7-3		Created.
 ****************************************************************************
 **/
package com.me.server;

import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 服务器端登录人员DTO. <br/>
 * 上午9:26:10 2012-7-3
 * 
 * @Author <a href="mailto:mestudying@sina.com">Junwei Zhang</a><br/>
 **/
public class JTalkerMember {
	public static final String USER_TYPE_WEBCLIENT = "webclient";
	public static final String USER_TYPE_PERSISTENT = "persistent";
	public static final String USER_TYPE_CHATROOM = "chatroom";

	/** User name. */
	private String userName = null;
	/** User status. */
	private String userStatus = null;
	private String userSID = null;
	private String userIP = "127.0.0.1";
	private String userPort = null;
	private String userType = JTalkerMember.USER_TYPE_PERSISTENT;
	private String userRole = MessageParser.GlobalUser.USER;
	private boolean login = false;

	private List<Message> messageQueue = new ArrayList<Message>();
	// private JTalkServerThread myThread = null;
	private String chatRoomAdmin = null;
	private List<String> chatRoomUsers = null;
	private boolean sessionClosed = false;
	private SocketChannel socketChannel = null;
	private JTalkProtocal protocal = null;
	private String sendText = null;
	public JTalkServer parent = null;
	
	public JTalkerMember(JTalkServer parent, SocketChannel socketChannel){
		this.parent = parent;
		this.socketChannel = socketChannel;
		this.userPort = String.valueOf(this.socketChannel.socket().getPort());
	}

	public JTalkerMember(JTalkServer parent, String userName, String userIP, String userPort, String userStatus, String userType) {
		this.parent = parent;
		this.userName = userName;
		this.userIP = userIP != null ? userIP : "server";
		this.userStatus = userStatus != null ? userStatus : "normal";
		this.userPort = userPort != null ? userPort : "-1";
		if (userType == null) {
			this.userType = JTalkerMember.USER_TYPE_PERSISTENT;
		} else {
			this.userType = userType;
		}
		this.userSID = this.generateSessionID();
	}

	/** 生成Session ID */
	private String generateSessionID() {
		return this.userPort + System.currentTimeMillis();
	}

	public String getUserName() {
		return userName;
	}

	public String getUserPort() {
		return userPort;
	}

	public String getUserStatus() {
		return userStatus;
	}

	public String getUserIP() {
		return userIP;
	}

//	public void setThread(JTalkServerThread thread) {
//		this.myThread = thread;
//	}

	/**
	 * Send the update message to this member.
	 */
	public void sendUpdateRequest() {
//		boolean sendResult = false;
		String message = "<JTALKER><" + MessageParser.MESSAGE
				+ " content=\"[UPDATE] You have new messages.\" type=\"update\"/></JTALKER>";
		this.setSendText(message);
//		if (this.myThread != null) {
//			this.parent.
//			sendResult = true;
//		} else {
//			sendResult = false;
//		}
//		return sendResult;
	}

	public int getPort() {
		return Integer.parseInt(this.userPort);
	}

	/**
	 * 增加一条消息.
	 * 
	 * @param tempMessage
	 * @param userName2
	 * @param messageType
	 * @param messageSubject
	 * @param messageID
	 * @return
	 */
	public boolean addMessage(String content, String sender, String type, String subject, String id) {
		// TODO Auto-generated method stub
		if(this.userType.equals(JTalkerMember.USER_TYPE_CHATROOM)){
			if(!type.equals("file")){
				content = "&lt;b&gt;" + sender + ":&lt;/b&gt; " + content;
			}
			sender = this.userName;
		}
		this.messageQueue.add(new Message(content, sender, type, subject, id));
		this.sendUpdateRequest();
		return true;
	}

	/**
	 * 获取用户信息.
	 * 
	 * @return
	 */
	public String getUserInfo() {
		return (this.userName + "@" + this.userIP);
	}

	public class Message {

		public String content = null;
		public String sender = null;
		public String type = null;
		public String subject = null;
		public String ID = null;

		public Message(String content, String sender, String type, String subject, String id) {
			this.content = content;
			this.sender = sender;
			this.type = type == null ? "normal" : type;
			this.subject = subject;
			this.ID = id;
		}
	}

	/**
	 * 返回消息数.
	 * 
	 * @return
	 */
	public int numOfMsgs() {
		return this.messageQueue.size();
	}

	/**
	 * 从消息队列中获取一条消息.
	 * 
	 * @return
	 */
	public synchronized Message getMessage() {
		// TODO Auto-generated method stub
		Message m = null;
		if (!this.messageQueue.isEmpty()) {
			m = this.messageQueue.get(0);
			this.messageQueue.remove(0);
		}
		return m;
	}

	/**
	 * 设置聊天室管理员.
	 * 
	 * @param callerName
	 */
	public boolean setChatRoomAdmin(String admin) {
		// TODO Auto-generated method stub
		if (!this.isChatRoom()) {
			return false;
		}
		if (admin == null || admin.length() < 1) {
			return false;
		}
		this.chatRoomAdmin = admin;
		JTalkerMember adminMember = this.parent.getMember(admin);
		this.socketChannel = adminMember.socketChannel;
		return this.addChatRoomUser(admin);
	}

	/**
	 * 添加聊天室成员.
	 * 
	 * @param user
	 * @return
	 */
	private boolean addChatRoomUser(String user) {
		// TODO Auto-generated method stub
		if (!this.isChatRoom()) {
			return false;
		}
		if (user == null || user.length() < 1) {
			return false;
		}
		if (this.chatRoomUsers == null) {
			this.chatRoomUsers = new ArrayList<String>();
		}
		if (!this.isChatRoomUser(user)) {
			this.chatRoomUsers.add(user);
		} else {
			return false;
		}
		return false;
	}

	/**
	 * 判断用户是否为聊天室人员.
	 * 
	 * @param user
	 * @return
	 */
	public boolean isChatRoomUser(String user) {
		if (!this.isChatRoom()) {
			return false;
		}
		String[] chatRoomUsers = this.getChatroomUsers();
		for (String u : chatRoomUsers) {
			if (u.equals(user)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取聊天室所有登录人员.
	 * 
	 * @return
	 
	private String[] getChatRoomUsers() {
		if (!this.isChatRoom() || this.chatRoomUsers == null) {
			return new String[0];
		}
		String[] users = new String[this.chatRoomUsers.size()];
		users = this.chatRoomUsers.toArray(users);
		return users;
	}*/

	/**
	 * 判断Member是否是聊天室.
	 * 
	 * @return
	 */
	public boolean isChatRoom() {
		return this.userType.equals(JTalkerMember.USER_TYPE_CHATROOM);
	}

	/**
	 * 设置聊天室成员.
	 * 
	 * @param users
	 */
	public boolean setChatRoomUsers(String users) {
		// TODO Auto-generated method stub
		if (!this.isChatRoom() || users == null || users.length() < 1) {
			return false;
		}
		if (this.chatRoomUsers == null) {
			this.chatRoomUsers = new ArrayList<String>();
		} else {
			this.chatRoomUsers.clear();
		}
		String[] tempUsers = users.split(",");
		for (String u : tempUsers) {
			if(JTalkServer.isAllowedUserName(u) && !this.isChatRoomUser(u)){
				this.chatRoomUsers.add(u);
			}
		}
		this.makeChatRoomUserListUnique();
		return true;
	}

	/**
	 * 设置聊天室不存在重复的成员.
	 */
	private boolean makeChatRoomUserListUnique() {
		if (!this.isChatRoom()) {
			return false;
		}
		String tempName = null;
		int numOfHits = 0;
		boolean retVal = true;
		for (int i = 0; i < this.chatRoomUsers.size(); i++) {
			tempName = this.chatRoomUsers.get(i);
			numOfHits = 0;
			for (int j = 0; j < this.chatRoomUsers.size(); j++) {
				if (tempName.equals(this.chatRoomUsers.get(j))) {
					numOfHits++;
					if (numOfHits > 1) {
						this.chatRoomUsers.remove(j);
						numOfHits--;
						j--;
						retVal = false;
					}
				}
			}
		}
		return retVal;
	}

	/**
	 * 获取聊天室管理员. 
	 * @return
	 */
	public String getChatroomAdmin() {
		if(!this.isChatRoom()){
			return "";
		}
		return this.chatRoomAdmin;
	}

	/**
	 * 获取聊天室所有成员.
	 * @return
	 */
	public String[] getChatroomUsers() {
		if(!this.isChatRoom() || this.chatRoomUsers == null){
			return new String[0];
		}
		String[] users = new String[this.chatRoomUsers.size()];
		this.chatRoomUsers.toArray(users);
		return users;
	}

	public int getUserRoleValue() {
		if(this.userRole.equals(MessageParser.GlobalUser.USER)){
			return 0;
		}else if(this.userRole.equals(MessageParser.GlobalUser.ADMIN)){
			return 1;
		}else if(this.userRole.equals(MessageParser.GlobalUser.ROOT)){
			return 2;
		}else{
			return -1;
		}
	}

	public void setUserRole(String role) {
		this.userRole = role;
	}

	/**
	 * 向聊天室增加一个成员.
	 */
	public boolean addChatroomUser(String user) {
		// TODO Auto-generated method stub
		if(!this.isChatRoom() || user == null){
			return false;
		}
		if(this.chatRoomUsers == null){
			this.chatRoomUsers = new ArrayList<String>();
		}
		if(!this.isChatRoomUser(user)){
			this.chatRoomUsers.add(user);
		}else{
			return false;
		}
		return true;
	}

	/**
	 * 获取所有消息并将其从消息队列中删除.
	 * @return
	 */
	public Message[] getMessages() {
		// TODO Auto-generated method stub
		Message[] msgs = new Message[this.messageQueue.size()];
		this.messageQueue.toArray(msgs);
		this.messageQueue.clear();
		return msgs;
	}

	/**
	 * 向消息队列中添加消息.
	 * @param msgs
	 */
	public boolean addMessages(Message[] msgs) {
		// TODO Auto-generated method stub
		for(Message m : msgs){
			this.messageQueue.add(new Message(m.content, m.sender, m.type, m.subject, m.ID));
		}
		this.sendUpdateRequest();
		return true;
	}

	/**
	 * 删除聊天室成员.
	 * @param userName
	 * @return
	 */
	public boolean removeChatrommUser(String userName) {
		if(!this.isChatRoom() || userName == null || userName.length() < 1){
			return false;
		}
		if(this.isChatRoomUser(userName)){
			for(String u : this.chatRoomUsers){
				if(userName.equals(u)){
					this.chatRoomUsers.remove(u);
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 关闭会话.
	 * @return
	 */
	public boolean closeSession() {
		// TODO Auto-generated method stub
		if(this.userType.equals(USER_TYPE_PERSISTENT)){
			return false;
		}
		this.sessionClosed  = true;
		return true;
	}

	/**
	 * 设置用户状态."Busy" "normal"
	 * @param memberStatus
	 */
	public void sendUserStatus(String status) {
		// TODO Auto-generated method stub
		if(!status.equalsIgnoreCase(this.userStatus)){
			this.userStatus = status;
//			this.sendUpdateRequestToAll();
		}
	}

	/**
	 * 向所有用户发送消息.
	 */
//	private boolean sendUpdateRequestToAll() {
//		if(this.myThread != null){
//			this.myThread.parent.sendUpdateRequestToAll(this.userName);
//			return true;
//		}else{
//			return false;
//		}
//	}

	public JTalkProtocal getProtocal() {
		return protocal;
	}

	public void setProtocal(JTalkProtocal protocal) {
		this.protocal = protocal;
	}

	public String getSendText() {
		return sendText;
	}

	public void setSendText(String sendText) {
		this.sendText = sendText;
		if(sendText != null){
			this.parent.setSocketChannelWritable(this.socketChannel);
		}
	}

	public String getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		this.userType = userType;
	}

	public String getUserRole() {
		return userRole;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public void setUserStatus(String userStatus) {
		this.userStatus = userStatus;
	}

	public void setUserIP(String userIP) {
		this.userIP = userIP;
	}

	public void setUserPort(String userPort) {
		this.userPort = userPort;
	}

	public String getUserSID() {
		return userSID;
	}

	public void setUserSID(String userSID) {
		this.userSID = userSID;
	}

	public boolean isLogin() {
		return login;
	}

	public void setLogin(boolean login) {
		this.login = login;
	}

}
